package com.park.controller;

import com.park.common.bean.GoodInputView;
import com.park.common.bean.PageBean;
import com.park.common.bean.ResponseBean;
import com.park.common.exception.MessageException;
import com.park.common.poo.ActivityInfo;
import com.park.common.util.JsonUtils;
import com.park.platform.service.IActivityService;
import com.park.platform.service.IGoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("good")
public class GoodController extends BaseController {

    @Autowired
    private IGoodService goodService;

    @Autowired
    private IActivityService activityService;

    @RequestMapping(value = "getGoods")
    public String getGoods(GoodInputView goodInputView, Model model) {
        try {
            model.addAllAttributes(JsonUtils.fromJsonDF(goodInputView));
            PageBean pageBean = goodService.getGoods(goodInputView);
            super.setPageInfo(model, pageBean);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Goods/GoodsList";
    }

    @RequestMapping("viewGood")
    public String viewGood(Integer goodId, Model model){
        if(goodId != null) {
            model.addAllAttributes(JsonUtils.fromJsonDF(activityService.getActivityInfo(goodId)));
        }
        return "Goods/GoodsViews";
    }

    /**
     * 保存或者更新商品的信息, 包括商品的图片上传
     * @param multipartRequest
     * @return
     */
    @ResponseBody
    @RequestMapping("saveGood")
    public ResponseBean saveGood(ActivityInfo activityInfo, MultipartHttpServletRequest multipartRequest){
        try {
            Integer goodId = goodService.saveGood(activityInfo, multipartRequest);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("goodId", goodId);
            return new ResponseBean(data);
        } catch (MessageException e) {
            e.printStackTrace();
            return new ResponseBean(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseBean(false);
        }
    }

    @ResponseBody
    @RequestMapping("deleteGood")
    public ResponseBean deleteGood(int activityId){
        try {
            goodService.newDeleteActivity(activityId);
            return new ResponseBean(true);
        } catch (MessageException e) {
            e.printStackTrace();
            return new ResponseBean(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseBean(false);
        }
    }
    
}
